package com.example.newnoke;


import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.FileProvider;
import android.view.View;

import com.example.newnoke.base.BaseReceive;
import com.example.newnoke.databinding.ActivityMainBinding;
import com.example.newnoke.fragment.main.ImFragment;
import com.example.newnoke.fragment.main.QklFragment;
import com.example.newnoke.fragment.main.ZiChanFragment;
import com.example.newnoke.mvp.presenter.TestPresenter;
import com.example.newnoke.mvp.view.ITestV;
import com.example.newnoke.view.dialog.HDDialgo;
import com.example.newnoke.view.dialog.UPDataDialgo;
import com.geya.jbase.baseactivity.BaseDetailsActivity;
import com.geya.jbase.uiview.ToastUtil;
import com.jpeng.jptabbar.OnTabSelectListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseDetailsActivity<TestPresenter> implements ITestV {

    private ActivityMainBinding mBinding;
    private List<Fragment> mFragmentList;
    private FragmentPagerAdapter mAdapter;

    private BaseReceive receive;

    @Override
    public TestPresenter newPresenter() {
        return new TestPresenter(this);
    }

    @Override
    public void init() {

        mTitleButton.getrImg().setVisibility(View.INVISIBLE);
        mTitleButton.setTitles("资产包");
        initReceive();
        initViewPager();
        applyJurisdiction();
//        checkVersion(4);
        if (getIntent().getBooleanExtra("show",false)){
            showHD(getIntent().getStringExtra("title"),
                    getIntent().getStringExtra("topic"),
                    getIntent().getStringExtra("desc"));
        }

    }

    @Override
    public void setContentView() {
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);

    }

    public void initViewPager() {

        mFragmentList = new ArrayList<>();
//        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new ZiChanFragment());
        mFragmentList.add(new QklFragment());
        mFragmentList.add(new ImFragment());



        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {

                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {

                return mFragmentList.size();
            }
        };

        mBinding.myViewpager.setAdapter(mAdapter);
        mBinding.myViewpager.setOffscreenPageLimit(5);
        initPagerBottomTabStrip();
    }

    public void initPagerBottomTabStrip() {

        mBinding
                .tabbar.setTitles( "资产包", "罗科链", "我的")
                .setNormalIcons( R.mipmap.tab_22, R.mipmap.tab_32, R.mipmap.tab_42)
                .setSelectedIcons( R.mipmap.tab_21, R.mipmap.tab_31,R.mipmap.tab_41)
                .generate();
//        //显示圆点模式的徽章
//        mBinding.tabbar.showBadge(3,4,false);
//        //设置容器
        mBinding.tabbar.setContainer(mBinding.myViewpager);
        mBinding.tabbar.setSelectTab(0);
        mBinding.tabbar.setTabListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int index) {

                switch (index){
                    case 0:
                        mTitleButton.setVisibility(View.VISIBLE);
                        mTitleButton.setTitles("资产包");
                        break;
                    case 1:
                        mTitleButton.setVisibility(View.VISIBLE);
                        mTitleButton.setTitles("罗科链");
                        break;
                    case 2:
                        mTitleButton.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public boolean onInterruptSelect(int index) {
                return false;
            }
        });
//        //设置Badge消失的代理
//        mBinding.tabbar.setDismissListener(this);


    }
    private void initReceive() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("IS_LOGIN");
        receive = new BaseReceive();
        //注册广播接收
        registerReceiver(receive, filter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receive != null) {
            unregisterReceiver(receive);
            receive = null;
        }
//        OkGoModel.mDisposable.dispose();

    }

    private int getVersionCode() {
        PackageManager pm = getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return 0;
    }

    /**
     * 申请权限
     */
    public void applyJurisdiction() {

        AndPermission.with(this)
                .requestCode(101)//
                .permission( Permission.STORAGE)//WRITE_EXTERNAL_STORAGE
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale).show();
                    }
                })
                .start();
    }


    private File mFile;

    private void checkVersion(int code) {
        //TODO 版本检测 (新版增加下载进度显示)
//        File file2=getActivity().getExternalCacheDir();
//        System.out.println("---------------------- 安卓路径 " + file2.getPath());
        int version = getVersionCode();


            if (code > version) {

//                showVersion(bean);

                UPDataDialgo dialgo = new UPDataDialgo();

                Bundle bundle = new Bundle();
                bundle.putString("content","1.2.3.3.4.5" );
                bundle.putString("url","" );
                dialgo.setArguments(bundle);
                dialgo.show(getSupportFragmentManager(), new UPDataDialgo.PayCallBack() {
                    @Override
                    public void installation(File file) {
                        // file 即为文件数据，文件保存在指定目录
                        mFile = file;
                        //兼容8.0
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
                            if (!hasInstallPermission) {
//                            ToastUtil.makeText(MyApplication.getContext(), MyApplication.getContext().getString(R.string.string_install_unknow_apk_note), false);
                                startInstallPermissionSettingActivity();
                                return;
                            }
                        }
                        checkIsAndroidO(mFile);
                    }

                    @Override
                    public void onError(String msg) {

                        ToastUtil.showShort(msg.equals("")?"下载失败":msg);

                    }
                });

            }


    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP);
    }

    /**
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */
    private void checkIsAndroidO(File file) {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean canRequestPackageInstalls = getPackageManager().canRequestPackageInstalls();
            if (canRequestPackageInstalls) {
                openAPK(file);
            } else {
                //请求安装未知应用来源的权限
                openAPK(file);
//                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 10010);
            }
        } else {
            openAPK(file);
        }

    }

    /**
     * 打开apk
     */
    private void openAPK(File file) {
        try {
            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0 以上
                String authority = getApplicationContext().getPackageName() + ".fileProvider";
                Uri apkUri = FileProvider.getUriForFile(this, authority, file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
              startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           startActivity(install);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final int REQUEST_CODE_UNKNOWN_APP = 2001;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10012:
//                String root = Environment.getExternalStorageDirectory().getPath();
//                File file = new File(root, "yaofenqi.apk");
                checkIsAndroidO(mFile);
                break;
            case REQUEST_CODE_UNKNOWN_APP:
                if (mFile != null) {
                    checkIsAndroidO(mFile);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
//            switch (requestCode) {
//                case REQUEST_CODE_PERMISSION_SINGLE: {
//                    // TODO do something.
//                    Toast.makeText(ListenerActivity.this, R.string.successfully, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//                case REQUEST_CODE_PERMISSION_MULTI: {
//                    // TODO do something.
//                    Toast.makeText(ListenerActivity.this, R.string.successfully, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
//            switch (requestCode) {
//                case REQUEST_CODE_PERMISSION_SINGLE: {
//                    // TODO The strategy after failure.
//                    Toast.makeText(ListenerActivity.this, R.string.failure, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//                case REQUEST_CODE_PERMISSION_MULTI: {
//                    // TODO The strategy after failure.
//                    Toast.makeText(ListenerActivity.this, R.string.failure, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
//            if (AndPermission.hasAlwaysDeniedPermission(ListenerActivity.this, deniedPermissions)) {
//                // 第一种：用默认的提示语。
//                AndPermission.defaultSettingDialog(ListenerActivity.this, REQUEST_CODE_SETTING).show();
//
//                // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(MainActivity.this)
                    .setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .show();


////            第三种：自定义dialog样式。
////            SettingService settingService = AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
////            你的dialog点击了确定调用：
////            settingService.execute();
////            你的dialog点击了取消调用：
////            settingService.cancel();
//            }
        }
    };


    public void showHD(String title,String content,String unit){
        HDDialgo dialgo = new HDDialgo();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("content", content);
        bundle.putString("unit",unit);

        dialgo.setArguments(bundle);
        dialgo.show(getSupportFragmentManager(), new HDDialgo.PayCallBack() {
            @Override
            public void installation(File file) {

            }

            @Override
            public void onError(String msg) {


            }
        });
    }


}
